
package assigment2;

import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.ext.DefaultHandler2;
import org.xml.sax.helpers.DefaultHandler;


public class StudentList {

    public static void main(String[] args) {
        try {
            SAXParserFactory f = SAXParserFactory.newInstance();
            SAXParser parser = f.newSAXParser();
            StudentHandler  shl = new StudentHandler();
            System.out.println("123");
            parser.parse(StudentList.class.getResourceAsStream("Student.xml"), shl);
            List<Personal> p = shl.getList();
            for(Personal i :p){
                System.out.println(p);
            }
            System.out.println("456");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
    class StudentHandler extends DefaultHandler{
        List<Personal> list;

        public StudentHandler(){
            list = new LinkedList<Personal>();
        }

        public List<Personal>getList(){
            return list;
        }

        private boolean studentFound = false;
        private boolean nameFound = false;
        private boolean rollNoFound = false;
        private boolean classnoFound = false;
        private boolean emailFound = false;

        private Personal currentPersonal;

    @Override
    public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes attributes) throws SAXException {
        if(qName.equals("student")){
            currentPersonal = new Personal();
            list.add(currentPersonal);
            studentFound = true;
        }
        if(qName.equals("name")){
            nameFound = true;
        }
        if(qName.equals("rollno")){
            rollNoFound = true;
        }
        if(qName.equals("classno")){
            classnoFound = true;
        }
        if(qName.equals("email")){
            emailFound = true;
        }
    }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if(nameFound){
                String name = new String(ch, start, length);
                currentPersonal.setName(name);
                nameFound = false;
            }
            if(rollNoFound){
                String rollNo = new String(ch, start, length);
                currentPersonal.setRollno(rollNo);
                rollNoFound = false;
            }
            if(classnoFound){
                String classNo = new String(ch, start, length);
                currentPersonal.setClassno(classNo);
                classnoFound = false;
            }
            if(emailFound){
                String email = new String(ch, start, length);
                currentPersonal.setEmail(email);
                emailFound = false;
            }
        }
    }